package com.MusicWeb.servlet;

import com.MusicWeb.entity.User;
import com.MusicWeb.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");
        String acc = req.getParameter("account");
        String pwd = req.getParameter("password");
        User user = userService.login(acc, pwd);
        if (user != null) {
            //获取  token 仍会数据库中
            String token = new Date().getTime() + "";
            Cookie cookie = new Cookie("token", token);
            cookie.setMaxAge(3600 * 24 * 30);
            cookie.setPath("/");
            resp.addCookie(cookie);
            boolean t = userService.token(user.getId(), token);
            if (t == true) {
                if (user.getId()==1){
                    req.getSession().setAttribute("user", user);
                    req.getSession().setAttribute("msg", "登录成功："+user.getName());
                    resp.sendRedirect(req.getContextPath() + "/FunctionPage/MusicAdmin_music.jsp");
                }else {
                    req.getSession().setAttribute("user", user);
                    req.getSession().setAttribute("msg", "登录成功："+user.getName());
                    resp.sendRedirect(req.getContextPath() + "/FunctionPage/MusicHome.jsp");
                }
            }else {
                req.getSession().setAttribute("msg", "token获取失败");
            }
        } else {
            req.getSession().setAttribute("msg", "登录失败");
            resp.sendRedirect(req.getContextPath() + "/FunctionPage/MusicHome.jsp");
        }
    }
}
